home *** CD-ROM | disk | FTP | other *** search
/ Java Primer Plus / Java Primer Plus (Waite Group Proess)(1996).iso / chapter14 / prodcons.java < prev    next >
Text File  |  1995-12-31  |  2KB  |  95 lines

  1. /* Producer/Consumer problem */
  2.  
  3. /* The bounded buffer */ 
  4.  class theTray { 
  5.     
  6.   static final int traysize = 10;
  7.   static int count,posW,posF = 0;
  8.   static int tray[] = new int[traysize];
  9.  
  10.   /* put an egg if there is room */
  11.   public synchronized void layegg(int x) throws InterruptedException {
  12.     if (count == traysize) { 
  13.         System.out.println("Wippy waiting...");
  14.         wait();
  15.         }
  16.     count++;
  17.     tray[posW] = x;
  18.     posW = (posW + 1)%10;
  19.     System.out.println("Count: " + count + " Wippy laid egg #" + x);
  20.     if (count == 1) notify();
  21.     }
  22.  
  23.   /* remove an egg, if there are any */
  24.   public synchronized int getegg() throws InterruptedException {
  25.     int x;
  26.     if (count == 0) {
  27.         System.out.println("Farmer waiting...");
  28.          wait();
  29.         }
  30.     count--;
  31.     x = tray[posF];
  32.     posF = (posF+1)%10;
  33.     System.out.println("Count: " + count + " Farmer got egg #" + x);
  34.     if (count == traysize-1) notify();
  35.     return x;
  36.     }
  37.     }
  38.  
  39. /* The Producer */
  40.  class Wippy extends Thread {
  41.  
  42.   theTray B;
  43.   int q=200;
  44.  
  45.   Wippy(theTray B) { this.B = B; }
  46.  
  47.   public void run() {
  48.     int a=0;
  49.  
  50.     while (q-->0) {
  51.       try {
  52.     B.layegg(a);
  53.     a = (a+1)%100000;
  54.     sleep((int)(20*Math.random()));
  55.       } catch (InterruptedException e) ;
  56.     }
  57.      }
  58.    }
  59.  
  60.  
  61. /* The consumer */
  62.  class Farmer extends Thread {
  63.  
  64.   theTray B;
  65.   int q=200;
  66.  
  67.   Farmer(theTray B) { this.B = B; }
  68.  
  69.   public void run() {
  70.     int a=0;
  71.  
  72.     while (q-->0) {
  73.       try {
  74.     a = B.getegg();
  75.     sleep((int)(20*Math.random())+10);
  76.       } catch (InterruptedException e) ;
  77.     }
  78.    }
  79.   }
  80.         
  81.  
  82. /* class to start the process */
  83.  class runner {
  84.  
  85.     public static void main(String args[]) {
  86.     
  87.      theTray B = new theTray();
  88.      Wippy W = new Wippy(B);
  89.      Farmer F = new Farmer(B);
  90.     
  91.      W.start();
  92.      F.start();
  93.     }
  94.       }
  95.